package slap.http;

import java.io.Serializable;
import java.text.ParseException;
import java.util.Date;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import slap.paradigm.ModelsContext;
import slap.paradigm.Procedure;
import slap.paradigm.ProcedureV;
import slap.util.Time;

public abstract class Request extends ModelsContext implements Serializable {
	
	protected static final Logger logger = LoggerFactory.getLogger(Request.class);
	
	protected static ThreadLocal<Request> current = new ThreadLocal<Request>();

	public static void setCurrent(Request request){
		current.set(request);
	}
	
	public static Request current(){
		return current.get();
	}
	
	public Request() {
		timeStamp = new Date();
	}


	public Object callback;
	public Future<?> future;
	public boolean isNew;
	
	public String sessionId;
	public Date timeStamp;
	
	public abstract String method();
	
	public abstract String uri();
	
	public abstract String path();
	
	public abstract String domain();
	
	public abstract int port();
	
	public abstract String host();
	
	public abstract String paramString();
	
	public abstract String parameter(String pname);
	
	public abstract boolean secured(); 
	
	public abstract String remoteAddress();
	
	public abstract String contentType();
	
	public abstract String header(String headerName);
	
	public abstract boolean containsHeader(String headerName);
	
	public abstract Cookie cookie(String cookieName);
	
	public abstract String rawRequestString();
	
	public boolean isModified(long last) {
		last = (long) Math.floor(last / 1000) * 1000;
		if (!containsHeader(Header.Names.IF_MODIFIED_SINCE)) {
			return true;
		} else {
			try {
				Date browserDate = Time.httpFormatter.parse(
						header(Header.Names.IF_MODIFIED_SINCE));
				if (browserDate.getTime() >= last) {
					return false;
				}
			} catch (ParseException ex) {
				logger.error("Can't parse date", ex);
			}
			return true;
		}
	}

	public boolean acceptGzip() {
		String value = header(Header.Names.ACCEPT_ENCODING);
		if (value == null) {
			return false;
		}
		return value.indexOf("gzip") > -1;
	}
	
}